import cv2
import numpy as np


def cut_img(img, pixel_size):
    img_size = img.shape
    if img_size[0] != img_size[1]:
        if img_size[0] > img_size[1]:
            d = img_size[0] - img_size[1]
            img = img[(d // 2):(img_size[0] - d // 2), 0:img_size[1]]
        else:
            d = img_size[1] - img_size[0]
            img = img[0:img_size[0], (d // 2):(img_size[1] - d // 2)]
            #

    cv2.namedWindow("cutted", cv2.WINDOW_NORMAL)
    cv2.imshow("cutted", img)
    img_l = []
    sub_size = img.shape[0] // pixel_size[0]
    for i in range(8):
        for j in range(8):
            img_l.append(img[j*sub_size:(j+1)*sub_size, i*sub_size:(i+1)*sub_size])
    return img_l


def read_pic(path,ifshow = False, ifwrite = False):
    img = cv2.imread(path)
    if ifshow:
        cv2.namedWindow("yuantu", cv2.WINDOW_NORMAL)
        cv2.imshow("yuantu", img)
    if ifwrite:
        cv2.imwrite("yuantu.jpg", img)
    return img


def bin_Pic(img, kernel, range, ifshow=False, ifwrite=False):
    g_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    bl_img = cv2.blur(g_img, kernel)
    _, th_img = cv2.threshold(bl_img, thresh=range[0], maxval=range[1], type=cv2.THRESH_BINARY)
    if ifshow:
        cv2.namedWindow("thresh", cv2.WINDOW_NORMAL)
        cv2.imshow("thresh", th_img)
    if ifwrite:
        cv2.imwrite("thresh.jpg", img)
    img_l = cut_img(th_img, pixel_size)
    return img_l


def pixel(img_list, pixel_size):
    sub_size = img_list[0].shape[0]**2
    pixel_space = np.zeros(shape=pixel_size,dtype=int)
    for a in range(len(img_list)):
        sub_img = img_list[a] / 255
        if sub_img.sum() / sub_size > 0.5:
            pixel_space[a // 8][a % 8] = 1
        else:
            pixel_space[a // 8][a % 8] = 0
    return pixel_space


def dec2hex(code):
    c = []
    dir = {10:"a",11:"b",12:"c",13:"d",14:"e",15:"f"}
    for i in code:
        if i > 9:
            c.append(dir[i])
        else:
            c.append(str(i))
    return c



def pix_code(pixel_space):
    file = open("code.txt", "w")
    for i in pixel_space:
        code = [0, 0]
        for j in range(4):
            code[0] *= 2
            code[0] += i[j]
        for j in range(4):
            code[1] *= 2
            code[1] += i[j+4]
        code_out = dec2hex(code)
        file.write("0x")
        for s in code_out:
            file.write(s)
        file.write(",")




if __name__ == "__main__":
    pixel_size = (8, 8)
    img_path = "test.jpg"
    img = read_pic(img_path,ifshow=True)
    img_list = bin_Pic(img, (5, 5), (170, 256), ifshow=True)
    pixel_space = pixel(img_list, pixel_size)
    pix_code(pixel_space)

    cv2.waitKey(0)
    cv2.destroyAllWindows()
